package volatilelearn;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Vector;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 本事例为了说明volatile修饰符并不能保证线程安全
 * 
 * volatile确保每次读取变量为最新的值
 * 
 * @author 10255_000
 *
 */
public class Counter1 {
	public volatile static int count = 0;//添加volatile修饰符
	
	public Vector vector = new Vector();
	public List list1 = new ArrayList();
	public List list2 = new LinkedList();

	public static void add() {
		try {
			Thread.currentThread().sleep(1000);//休眠1s
		} catch (Exception e) {
			e.printStackTrace();
		}
		count++;//加1
	}

	public static void main(String[] args) {
		Thread threads[]=new Thread[1000];
		
		Lock lock = new ReentrantLock ();
		
		Queue queue =new ConcurrentLinkedQueue();
		
		for (int i = 0; i < 1000; i++) {
			threads[i] = new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Counter1.add();
				}

			});
			threads[i].start();
		}
		
		for (int i = 0; i < 1000; i++) {
			try{
				threads[i].join();
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				System.out.println("运行结果:Counter1.count=" + Counter1.count);
			}
		}
	}
}
